const cheerio = require('cheerio');
const curl = require('./curl');
const xlsx = require('./xlsx');

const get_world_data = function () {
  const url = "https://c.m.163.com/ug/api/wuhan/app/data/list-total";

  return new Promise(function (resolve, reject) {
    curl.download(url, function (res) {
      if (res) {
        let res_json = JSON.parse(res);
        console.log('获取网易数据成功！');
        resolve(res_json);
      } else {
        reject('获取网易数据失败！')
      }
    })
  });
}

const get_data = async function (file) {
  let n_data = await get_world_data();

  let lastUpdateTime = n_data.data.lastUpdateTime;
  let areaTree_list = n_data.data.areaTree;
  let chinaDay_list = n_data.data.chinaDayList;
  let chinaTotal = n_data.data.chinaTotal;

  let headers = ['今日确诊', '今日死亡', '今日治愈', '今日疑似', '确诊总数', '死亡总数', '治愈总数', '疑似总数'];

  let world_array = [
    ['编码', '国家', ...headers, '更新时间']
  ];

  let china_array = [
    ['编码', '名称', ...headers]
  ];

  let china_day_array = [
    ['时间', ...headers]
  ];

  const resolve_data = function (array, items, deep = false) {
    array.forEach(ele => {
      items.push([
        ele.id, ele.name, ele.today.confirm, ele.today.dead, ele.today.heal, ele.today.suspect,
        ele.total.confirm, ele.total.dead, ele.total.heal, ele.total.suspect, lastUpdateTime
      ]);

      if (deep) {
        resolve_data(ele.children, items, deep);
      }
    });
  }

  resolve_data(areaTree_list, world_array);
  resolve_data(areaTree_list[0].children, china_array, true);

  chinaDay_list.forEach(ele => {
    china_day_array.push([
      ele.date, ele.today.confirm, ele.today.dead, ele.today.heal, ele.today.suspect,
      ele.total.confirm, ele.total.dead, ele.total.heal, ele.total.suspect
    ]);
  });

  let chinaTotal_array = [
    ['确诊', chinaTotal.total.confirm],
    ['死亡', chinaTotal.total.dead],
    ['治愈', chinaTotal.total.heal],
    ['疑似', chinaTotal.total.suspect],
    ['确诊变化', chinaTotal.today.confirm],
    ['死亡变化', chinaTotal.today.dead],
    ['治愈变化', chinaTotal.today.heal],
    ['疑似变化', chinaTotal.today.suspect],
    ['时间', lastUpdateTime]
  ];

  let new_file = new xlsx.Xlsx(file);

  new_file.add({
    name: '国际情况',
    data: world_array
  });

  new_file.add({
    name: '国内情况',
    data: chinaTotal_array
  });

  new_file.add({
    name: '各地情况',
    data: china_array
  });

  new_file.add({
    name: '国内每日',
    data: china_day_array
  });

  await new_file.writeFileSync();
}

exports.get_data = get_data;